package com.happyhome.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.happyhome.constants.ComUnitName;
import com.happyhome.constants.RecordStatus;
import com.happyhome.datamodel.Image;
import com.happyhome.datamodel.QHouse;
import com.happyhome.datamodel.QImage;
import com.happyhome.datamodel.QUser;
import com.happyhome.datamodel.User;
import com.mysema.query.BooleanBuilder;
import com.mysema.query.jpa.JPQLQuery;
import com.mysema.query.jpa.impl.JPAQuery;
import com.trg.dao.jpa.GenericDAOImpl;

@Repository
public class UsersDaoImpl extends GenericDAOImpl<User, Long> implements UsersDao{
	
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(UsersDaoImpl.class);
	
	@Override
	@PersistenceContext(unitName = ComUnitName.COM_UNIT)
	public void setEntityManager(EntityManager entityManager) {
		super.setEntityManager(entityManager);
	}

	@Override
	public List<User> getAllUsers() {
		JPQLQuery query = new JPAQuery(em());
		QUser users = QUser.user;
		
		query.from(users);
		
		BooleanBuilder where = new BooleanBuilder();
		
		where.and(users.status.eq(RecordStatus.TRUE));
		
		query.where(where);
		
		List<User> listUsers = query.list(users);
		return listUsers;
	}

	@Override
	public User getUserByUserName(String username) {
		JPQLQuery query = new JPAQuery(em());
		QUser users = QUser.user;
		
		query.from(users);
		
		BooleanBuilder where = new BooleanBuilder();
		
		where.and(users.status.eq(RecordStatus.TRUE))
			 .and(users.username.eq(username));
		
		query.where(where);
		
		User user = query.uniqueResult(users);
		return user;
	}

	@Override
	public Long getImageOfManager(Long idHouse) {
		JPQLQuery query = new JPAQuery(em());
		QUser users = QUser.user;
		QHouse house = QHouse.house;
		QImage image = QImage.image;
		
		BooleanBuilder where = new BooleanBuilder();
		
		where.and(house.status.eq(RecordStatus.TRUE)).and(house.idHouse.eq(idHouse));
		
		query.from(house).where(where).leftJoin(house.user, users).leftJoin(users.images, image);
		
		List<Image> listImages = query.list(image);
		if(listImages != null && listImages.size() > 0){
			return listImages.get(0).getId();
		}
		return null;
	}

}
